using System.Reflection;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.HttpOverrides;
using Serilog;

var builder = WebApplication.CreateBuilder(args);

var configuration = builder.Configuration;
var hostEnvironment = builder.Environment;

//配置 本地 Configuration 目录下json文件
builder.Configuration.AddConfigurationJsonFiles(hostEnvironment);

builder.AddServiceDefaults();

// Add services to the container.

var services = builder.Services;

try
{
    //add SageKing
    builder.Services.AddSageKing(sk =>
    {
        //MediaR
        sk.UseIceMediatR(o => o.MediatRServiceConfiguration += a =>
        {
            a.RegisterServicesFromAssemblies(typeof(Program).Assembly);
        });

        //us log
        sk.UseSageKingLogSerilog();

        //use yarp
        sk.UseSageKingAPIGatewayYarp();

    }, configuration, hostEnvironment);

    //other service add
    services.AddCors();

    builder.Services.AddRazorPages();

    Log.Information("Starting web ApiGateway host");

    ////////////////////////builld
    ///
    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        // 开发环境：使用开发者异常页面，显示详细错误信息
        app.UseDeveloperExceptionPage();

    }
    else
    {
        // 生产环境：使用异常处理中间件，跳转到自定义错误路径或执行逻辑
        app.UseSageKingResultExceptionHandler(configuration);
    }

    app.UseStaticFiles();

    //app.UseHttpsRedirection();

    app.UseRequestLocalization();

    app.UseRouting();

    app.UseCors("*");

    //Use SageKing
    app.UseSageKingInit(configuration, hostEnvironment);

    app.MapRazorPages();

    app.MapDefaultEndpoints();

    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "Host terminated unexpectedly");
    return 1;
}
finally
{
    Log.CloseAndFlush();
}

return 0;